import React from 'react';
import { Card, Button, Table, Space, Modal, message, TableProps } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaSkillCertificatesSrv } from '@/service/teacher';
import { CERTIFICATE_TYPE, LANGUAGE, OTHER_PROFICIENCY, PROFICIENCY } from '@/constant/teachOptions';
import { isPermissionOperate } from '@/component/permission-button';

const SkillQual: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const columns: TableProps['columns'] = [
    {
      title: '语种',
      dataIndex: 'language',
      key: 'language',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(LANGUAGE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '掌握程度',
      dataIndex: 'proficiency_level',
      key: 'proficiency_level',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(PROFICIENCY, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '其他技能名称',
      dataIndex: 'other_skill_name',
      key: 'other_skill_name',
    },
    {
      title: '其他技能掌握程度',
      dataIndex: 'other_skill_level',
      key: 'other_skill_level',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(OTHER_PROFICIENCY, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '证书类型',
      dataIndex: 'certificate_type',
      key: 'certificate_type',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(CERTIFICATE_TYPE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '语言证书名称',
      dataIndex: 'language_certificate_name',
      key: 'language_certificate_name',
    },
    {
      title: '发证年月',
      dataIndex: 'issue_year_month',
      key: 'issue_year_month',
    },
    {
      title: '发证单位',
      dataIndex: 'issuing_authority',
      key: 'issuing_authority',
    },
    {
      title: '证书编号',
      dataIndex: 'certificate_number',
      key: 'certificate_number',
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '语种',
          name: 'language',
          key: 'language',
          required: true,
          inputType: InputType.select,
          renderOption: LANGUAGE,
        },
        {
          label: '掌握程度',
          name: 'proficiency_level',
          key: 'proficiency_level',
          required: true,
          inputType: InputType.select,
          renderOption: PROFICIENCY,
        },
        {
          label: '其他技能名称',
          name: 'other_skill_name',
          key: 'other_skill_name',
          textRange: [0, 20],
        },
        {
          label: '其他掌握程度',
          name: 'other_skill_level',
          key: 'other_skill_level',
          inputType: InputType.select,
          renderOption: OTHER_PROFICIENCY,
        },
        {
          label: '证书类型',
          name: 'certificate_type',
          key: 'certificate_type',
          inputType: InputType.select,
          renderOption: CERTIFICATE_TYPE,
        },
        {
          label: '证书名称',
          name: 'language_certificate_name',
          key: 'language_certificate_name',
          textRange: [0, 20],
        },
        {
          label: '发证年月',
          name: 'issue_year_month',
          key: 'issue_year_month',
          inputType: InputType.date,
        },
        {
          label: '发证单位',
          name: 'issuing_authority',
          key: 'issuing_authority',
          textRange: [0, 20],
        },
        {
          label: '证书编号',
          name: 'certificate_number',
          key: 'certificate_number',
          textRange: [0, 20],
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();

  const [formValue, setFormValue] = React.useState({});
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaSkillCertificatesSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };

  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaSkillCertificatesSrv.detail(record.teacher_skill_certificates_id);

    const params = {
      ...data,
      //language: data.language ? data.language?.split(',') : [],
      //proficiency_level: data.proficiency_level ? data.proficiency_level?.split(',') : [],
      //other_skill_level: data.other_skill_level ? data.other_skill_level?.split(',') : [],
      //certificate_type: data.certificate_type ? data.certificate_type?.split(',') : [],
    };
    setCurrentRowId(record.teacher_skill_certificates_id);

    setFormValue(params);
    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除语种: ${record.language_certificate_name} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaSkillCertificatesSrv.delete(record.teacher_skill_certificates_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
    };
    params.issue_year_month = utils.formatTime(values.issue_year_month);
    //params.language = params.language?.join(',');
    //params.proficiency_level = params.proficiency_level?.join(',');
    //params.other_skill_level = params.other_skill_level?.join(',');
    //params.certificate_type = params.certificate_type?.join(',');
    if (isEdit) {
      params.teacher_skill_certificates_id = currentRowId;
    }
    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaSkillCertificatesSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="技能及资格" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '技能及资格编辑' : '技能及资格详情') : '技能及资格新增'}
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

SkillQual.defaultProps = {
  isEditPanel: true,
};

export default SkillQual;
